package com.zzj.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Random;

public class Utils {


    /**
     * 获取当前时间到凌晨的秒数
     * @return
     */
    public static  Long getSecondsNextEarlyMorning(){
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,1);
        calendar.add(Calendar.HOUR_OF_DAY,0);
        calendar.add(Calendar.SECOND,0);
        calendar.add(Calendar.MINUTE,0);
        calendar.add(Calendar.MILLISECOND,0);
        return (calendar.getTimeInMillis()-System.currentTimeMillis())/1000;
    }

    /**
     * 重命名文件
     * @param file
     * @return
     * @throws IOException
     */
    public static MultipartFile rename(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String[] filename = originalFilename.split("\\.");
        File fileTemp= File.createTempFile("zblog-"+filename[0], "."+filename[1]);
        file.transferTo(fileTemp);

        fileTemp= FileUtil.rename(fileTemp, RandomUtil.randomString(10),true,true);
        InputStream inputStream  = new FileInputStream(fileTemp);
        file=new MockMultipartFile(fileTemp.getName(),inputStream);
        fileTemp.deleteOnExit();
        return file;
    }

    public static String getFileType(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String[] filename = originalFilename.split("\\.");
        return filename[1];
    }

    /**
     * 生成登录码
     * @param codeLength
     * @return
     */
    public static String generateRandomLoginCode(int codeLength) {
        // 生成登录码的字符集
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random rand = new Random();

            StringBuilder code = new StringBuilder();
            for (int i = 0; i < codeLength; i++) {
                int randomIndex = rand.nextInt(characters.length());
                code.append(characters.charAt(randomIndex));
            }
        return code.toString();
    }

    /**
     * 验证码生成
     */
    public static String getCode(int num){
        Random random=new Random();
        String code="";
        for (int i =0;i<num;i++){
            int rand= random.nextInt(10);
            code+=rand;
        }
        return code;
    }
}
